<?php


/**
 * User configuration management
 *
 * @author Sven Ruttloff, www.sruttloff.de <service@sruttloff.de>
 * @copyright S.Ruttloff, Computer Hard- & Software
 * @version 1
 * @package core
 * @license http://www.sruttloff.de/cms/files/licence_en_lgpl.txt LGPL
 */

/**
* user config management
*
* @package userconfig
* @version 1
*/
class userconfig
{
	private $c_arrayy = array ();
	private $USERID;
	/**
	 * Load user config file into memory
	 *
	 * @param      int       unique user id
	 * @return     void
	 */
	public function __construct ($userid = null)
	{
	    if (isset($userid))
	    {
			$this->load($userid);
	    }
	}
	/**
	* Load user config file into memory
	*
	* @param      int		unique user id
	* @return     void
	*/
	private function load($userid = null)
	{
		if (isset($userid))
		{
			$this->USERID = $userid;
		}
		$fn = CMSR_PATH_BASEDIR_SERVER . "/" . WRITEABLEADMINDIR . "/config/" . $this->USERID . ".cfg";
		if (file_exists($fn)) {
			$farr = file($fn);
			reset($farr);
			while (list ($k, $v) = each($farr)) {
				//exclude comments
				if (substr($v, 0, 1) != "#") {
					$v = substr($v, 0, strlen($v) - 1);
					$cfarr = split("::", $v);
					$this->c_arrayy[$cfarr[0]] = trim($cfarr[1]);
				}
			}
		}
	}
	/**
	* return a value of a item
	*
	* @param      string       	item
	* @return     mixed			false if var not exists else the var value
	*/
	public function Get($key)
	{
		if (isset ($this->c_arrayy[strtolower($key)]))
			return $this->c_arrayy[strtolower($key)];
		else
			return false;
	}

	private function save()
	{
		$frontend = frontend::getInstance();
		#die (debug_var ($this->c_arrayy));#
		$fn = CMSR_PATH_BASEDIR_SERVER . "/" . WRITEABLEADMINDIR . "/config/" . $this->USERID . ".cfg";
		$ttl = (string) null;
		@ reset($this->c_arrayy);
		while (list ($k, $v) = @ each($this->c_arrayy))
			$ttl .= "$k::$v\n";
		if (!create_file($fn, $ttl, $frontend->getConfig()->Get("chmod_files")))
			trigger_error('Can not write user config file', E_USER_ERROR);
		return true;
	}
	/**
	* set a value of a item
	*
	* @param      string        item
	* @param      string        value
	* @return     bool
	*/
	public function Set($key, $value)
	{
		$this->c_arrayy[strtolower($key)] = $value;
		return $this->save();
	}
}